package control
{
	import control.panel.PanelControl;
	
	import events.TableEvent;
	
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	
	import global.GameState;
	import global.GameType;
	import global.Resource;

	public class SoundControl extends PanelControl
	{
		private var isPlayAlarm:Boolean;
		private var alarmSoundChanel:SoundChannel;
		private var soundCS:Array = [];
		private var st:SoundTransform = new SoundTransform(0);
		
		public function SoundControl()
		{
			initListener();
			
		}
		
		private function initListener():void
		{
			_model.tableModel.addEventListener(TableEvent.ROUND_RESULT,onRoundResult);
			_model.tableModel.addEventListener(TableEvent.SHOW_CARDS,onShowCard);
			_model.tableModel.addEventListener(TableEvent.TABLE_ANIMATION,onTableAnimate);
		}
		
		private function onTableAnimate(event:TableEvent):void
		{
			playSound(event.soundId);
		}
		
		private function onShowCard(event:TableEvent):void
		{
			playSound(GameType.SOUND_SEND_CARD);
		}
		
		private function onRoundResult(event:TableEvent):void
		{
			if (event.roundResultData.winnerSitId != - 1)
			{
				playSound(GameType.SOUND_GOLD);
			}
		}
		
		public function playAlarm():void
		{
			if (isPlayAlarm == false)
			{
				alarmSoundChanel = playSound(GameType.SOUND_ALERM);
			}
			isPlayAlarm = true;
		}
		
		public function clearPlayAlarm():void
		{
			isPlayAlarm = false;
			st.volume = 0;
			if (alarmSoundChanel)
			{
				alarmSoundChanel.soundTransform = st;
			}
		}
		
		
		public function playSound(type:String):SoundChannel
		{
			
			var sound:Sound = Resource.getSound(type);
			if (sound)
			{
				var sc:SoundChannel = sound.play()
				sc.addEventListener(Event.SOUND_COMPLETE,onSoundComplete);
				soundCS.push(sc);
				if (GameState.isPlaySound)
				{
					st.volume = 1;
					
				}
				else
				{
					st.volume = 0;
				}
				sc.soundTransform = st;
				return sc;
			}
			return null;
		}
		
		private function onSoundComplete(event:Event):void
		{
			event.target.removeEventListener(Event.SOUND_COMPLETE,onSoundComplete);
			soundCS.splice( soundCS.indexOf(event.target),1);
		}
		
		public function switchOnOff():void
		{
			if (GameState.isPlaySound)
			{
				GameState.isPlaySound = false;
				stopAllSound();
			}
			else
			{
				GameState.isPlaySound = true;
				startAllSound();
			}
		}
		
		public function stopAllSound():void
		{
			
			st.volume = 0;
			var sc:SoundChannel;
			for (var i:String in soundCS)
			{
				sc = soundCS[i];
				sc.soundTransform = st;
			}
		}
		
		public function startAllSound():void
		{
			st.volume = 1;
			var sc:SoundChannel;
			for (var i:String in soundCS)
			{
				sc = soundCS[i];
				sc.soundTransform = st;
			}
		}
	}
}